//
//  WPCommunicationCommunityVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/10.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPCommunicationCommunityVC.h"
#import "WPCommunicationCommunityTVC.h"
#import "WPVideoModel.h"
#import "WPVideoDetailVC.h"

@interface WPCommunicationCommunityVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *models;
@property(nonatomic,assign)int indexPage;

@end

@implementation WPCommunicationCommunityVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    self.title = @"交流社区";
    self.view.backgroundColor = GlobalBgColor;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_highlight"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [backBtn sizeToFit];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    [self tableView];
    [self loadData];
}

-(void)loadData
{
    [self showWithStatus:@"正在加载"];
    
    NSString *url = @"video/findByPage.do";
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:@{@"page":@(0)} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            for (NSDictionary *dict in responseDict[@"detail"])
            {
                WPVideoModel *model = [WPVideoModel yy_modelWithDictionary:dict];
                [self.models addObject:model];
            }

            [self.tableView reloadData];
            [self dismiss];
        }
        else
        {
            [self showErrorInfoWithStatus:@"加载失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];
}

-(UITableView *)tableView
{
    if (_tableView == nil)
    {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = GlobalBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = SCREEN_WIDTH/VIDEO_SNAP_SCALE+10;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        [_tableView registerClass:[WPCommunicationCommunityTVC class] forCellReuseIdentifier:@"WPCommunicationCommunityTVC"];
        
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.equalTo(self.view);
        }];
        
        /* 配置下拉刷新控件 */
        MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //      刷新数据
            [self refreshData];
        }];
        self.tableView.mj_header = mj_header;
        [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
        [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
        [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
        mj_header.stateLabel.textColor = GLobalFontColor;
        mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
    }
    return _tableView;
}

#pragma mark - 数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPCommunicationCommunityTVC *cell = [tableView dequeueReusableCellWithIdentifier:@"WPCommunicationCommunityTVC"];
    cell.model = self.models[indexPath.item];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPVideoModel *model = self.models[indexPath.item];
    NSString *url = @"video/watch.do";
    NSDictionary *dict = @{@"id":@(model.id)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    WPCommunicationCommunityTVC *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    WPVideoDetailVC *vc = [WPVideoDetailVC new];
    vc.model = model;
    vc.videoImage = cell.videoImageView.image;
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(NSMutableArray *)models
{
    if (_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}


-(void)backBtnDidClick
{
    [self dismiss];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)refreshData
{
    NSString *url = @"video/findByPage.do";
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:@{@"page":@(0)} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            [self.models removeAllObjects];
            
            for (NSDictionary *dict in responseDict[@"detail"])
            {
                WPVideoModel *model = [WPVideoModel yy_modelWithDictionary:dict];
                
                [self.models addObject:model];
            }
            
            [self.tableView reloadData];
        }
        else
        {
            [self showErrorInfoWithStatus:@"加载失败"];
        }
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
        
    }];

}
@end
